package com.thitech.sif.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;

import com.thitech.sif.utils.log.LogFactory;
import com.thitech.sif.utils.log.SifLogger;

/**
 * IO工具类
 * @author shisheng.lian
 *
 */
public class IOUtils {
	private static SifLogger logger = LogFactory.getLogger(IOUtils.class);
	
	public static void closeQuietly(Reader input) {
		try {
			if (null != input) {
				input.close();
			}
		} catch (Exception e) {
			// ignore
		}
	}

	public static void closeQuietly(Writer output) {
		try {
			if (null != output) {
				output.close();
			}
		} catch (Exception e) {
			// ignore
		}
	}

	public static void closeQuietly(InputStream input) {
		try {
			if (null != input) {
				input.close();
			}
		} catch (Exception e) {
			// ignore
		}
	}

	public static void closeQuietly(OutputStream output) {
		try {
			if (null != output) {
				output.close();
			}
		} catch (Exception e) {
			// ignore
		}
	}
	
	public static InputStream getFileAsStream(String filePath) throws FileNotFoundException {
        InputStream inStream = null;
        File file = new File(filePath);
        if (file.exists()) {
            inStream = new FileInputStream(file);
        } else {
            inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        }
        return inStream;
    }
	
	/**
	 * 从各种渠道载入文件
	 * @param filePath
	 * @return
	 */
	public static InputStream loadFileInputStream(String filePath) {
        InputStream inStream = null;
        try {
            if (filePath.startsWith("file://")) {
                filePath = filePath.substring("file://".length());
                inStream = IOUtils.getFileAsStream(filePath);
            } else if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
                URL url = new URL(filePath);
                inStream = url.openStream();
            } else if (filePath.startsWith("classpath:")) {
                String resourcePath = filePath.substring("classpath:".length());
                inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
            } else {
                inStream = IOUtils.getFileAsStream(filePath);
            }

            if (inStream == null) {
            	logger.error("load config file error, file : " + filePath);
                return null;
            }
        } catch (Exception ex) {
        	logger.error("load config file error, file : " + filePath, ex);
            return null;
        }
        return inStream;
	}
}
